<script setup lang="ts">
import CopyOutlined from "@ant-design/icons-vue/CopyOutlined";
import {message} from "ant-design-vue";
import ProductCategory from "~/contentScripts/views/wxt/BatchAddingProducts/components/productCategory.vue";

// 选择宝贝Table
import {WxtBiddingConstraintType, WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode["消费者运营-拉新快"],
  },
  promotionScene: {
    type: String as PropType<WxtBiddingConstraintType>,
    default: WxtBiddingConstraintType.促进全店成交,
  },
});

enum Type {
  itemId = 'itemId',
  title = 'title',
}

const searchType = ref<Type>(Type.itemId);
const loading = ref(false);
const products = ref([]);
const search = ref('');
const categoryId = ref<number | undefined>(undefined);
const loadProducts = () => {
  loading.value = true;
  WxtUtils.customRequest('https://one.alimama.com/material/item/findPage.json', props.bizCode, {
    itemSelectedMode: 'userDefinedItem',
    materialType: 1,
    needQualification: true,
    itemIdList: searchType.value === Type.itemId ? (search.value ? search.value.split(",") : undefined) : undefined,
    // optimizeTarget: 'conv',
    promotionScene: props.promotionScene,
    promotionType: 'item',
    shopCategoryId: categoryId.value ? categoryId.value : undefined,
    subPromotionType: 'item',
    tagId: '1',
    title: searchType.value === Type.title ? (search.value ?? undefined) : undefined,
  }).then((res: any) => {
    if (res.data.info.ok) {
      products.value = res.data.data.list;
    }
  }).finally(() => {
    loading.value = false;
  });
};
const columns = [
  {
    title: '宝贝标题',
    dataIndex: 'title',
    dataType: 'custom',
    width: 300,
    slot: 'product',
    fixed: 'left',
  },
  ...props.bizCode === WxtBizCode.关键字推广 ? [{
    title: '冷启动状态',
    dataIndex: 'itemExtInfo.coldSpeedStatusName',
    dataType: 'custom',
    slot: 'coldSpeedStatusName',
    width: 160,
  },
    {
      title: '销量星级',
      dataIndex: 'itemExtInfo.salesLevel',
      width: 80,
    }, {
      title: '市场覆盖指数',
      dataIndex: 'itemExtInfo.marketCoverage',
      width: 120,
    }, {
      title: '店铺覆盖指数',
      dataIndex: 'itemExtInfo.attractInshopPv',
      width: 120,
    }, {
      title: '客户覆盖指数',
      dataIndex: 'itemExtInfo.customerCoverage',
      width: 120,
    }, {
      title: '近七天搜索点击量',
      dataIndex: 'itemExtInfo.clk7d',
      width: 140,
    }, {
      title: '近七天搜索点击率',
      dataIndex: 'itemExtInfo.ctr7d',
      width: 140,
      dataType: 'customRender',
      render: (text: any) => {
        if (!isNaN(text)) {
          return (text * 100).toFixed(2) + '%';
        } else {
          return '--';
        }
      }
    }, {
      title: '近7天销量',
      dataIndex: 'itemExtInfo.payCnt7d',
      width: 100,
    }, {
      title: '近30天销量',
      dataIndex: 'itemExtInfo.payCnt30d',
      width: 100,
    }, {
      title: '是否上车',
      dataIndex: 'itemExtInfo.hasAd',
      dataType: 'customRender',
      render: (text: any) => text ? '是' : '否',
      width: 100,
    },
  ] : [],
  ...([WxtBizCode.关键字推广, WxtBizCode.精准人群推广].includes(props.bizCode) ? [{
    title: '价格',
    dataIndex: 'price',
    width: 80,
    dataType: 'customRender',
    render: (text: number) => {
      return `￥${(text / 100).toFixed(2)}`;
    },
  }] : []),
  {
    title: '库存',
    dataIndex: 'quantity',
    width: 80,
  },
  {
    title: '销量',
    dataIndex: 'bidCount',
    width: 80,
  },
  {
    title: '发布时间',
    dataIndex: 'starts',
    align: 'right',
    width: 200,
  },
  {
    title: '首次发布时间',
    dataIndex: 'firstStartsTime',
    align: 'right',
    width: 200,
  },
];
const copy = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  });
}
onMounted(() => {
  loadProducts();
});
const selectRows = ref<any[]>([]);
const remove = (itemIds: number[]) => {
  // console.log(itemIds);
  // 从selectRows中移除
  selectRows.value = selectRows.value.filter((r) => !itemIds.includes(r.itemId));
}
const emit = defineEmits([
  "next",
  "update:value",
]);
watch(() => selectRows.value, (val) => {
  emit('update:value', val);
});
const tableBox = ref<HTMLDivElement | null>(null);
const tableWidth = ref(0);
watch(() => tableBox.value, (val) => {
  if (val) {
    tableWidth.value = val.clientWidth;
  }
}, {
  deep: true,
});
onMounted(() => {
  if (tableBox.value) {
    tableWidth.value = tableBox.value.clientWidth;
  }
  window.addEventListener('resize', () => {
    if (tableBox.value) {
      tableWidth.value = tableBox.value.clientWidth;
    }
  });
});
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    if (tableBox.value) {
      tableWidth.value = tableBox.value.clientWidth;
    }
  });
});
</script>

<template>
  <a-row type="flex" :gutter="16">
    <a-col flex="1" style="overflow: hidden;" ref="tableBox">
      <base-table :columns="columns" selection row-key="itemId" v-model:selected-rows="selectRows" :loading="loading"
                  pagination :data-source="products" title="店铺宝贝" :scroll="{
    y: 600,
    x: tableWidth,
  }"
      >
        <template #toolbar>
          <a-space>
            <product-category v-model:value="categoryId"/>
            <div>
              搜索类型：
              <a-select v-model:value="searchType" style="width: 100px" size="small">
                <a-select-option :value="Type.itemId">宝贝ID</a-select-option>
                <a-select-option :value="Type.title">宝贝标题</a-select-option>
              </a-select>
            </div>
            <a-input size="small" v-model:value="search"
                     :placeholder="searchType===Type.itemId?'可输入多个ID,分隔':'请输入宝贝标题'"
            />
            <a-button type="primary" size="small" @click="loadProducts" :loading="loading">搜索</a-button>
          </a-space>
        </template>
        <template #coldSpeedStatusName="row">
          <a-tag :color="row.itemExtInfo.coldSpeedStatus!='NOTALLOWED'?'blue':'gray'">
            {{ row.itemExtInfo.coldSpeedStatusName }}
          </a-tag>
        </template>
        <template #product="row">
          <a-row type="flex" class="adgroupName" :gutter="5">
            <a-col>
              <a-popover placement="right">
                <template #content>
                  <img :src="row.imgUrl"
                       style="width: 200px;height: 200px;"
                  />
                </template>
                <img :src="row.imgUrl"
                     style="width: 60px;height: 60px;border-radius: 5px;"
                />
              </a-popover>
            </a-col>
            <a-col flex="1" class="title">
              <a-tooltip :title="row.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.title }}</span>
              </a-tooltip>
              <div>
                <a-space>
                  <span style="color: #666;">ID: {{ row.itemId }}</span>
                  <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;" @click="copy(row.itemId)"/>
                </a-space>
              </div>
            </a-col>
          </a-row>
        </template>
      </base-table>
    </a-col>
    <div style="width: 350px;height:690px;border: 1px solid rgb(245, 245, 245);display: flex;flex-direction: column;">
      <a-row class="top">
        <a-col flex="1">
          已选 <span style="color: #1677ff;">{{ selectRows.length }}</span> 个宝贝
        </a-col>
        <a-col>
          <a-button size="small" danger type="link" @click="remove(selectRows.map((r)=>r.itemId))">全部移除</a-button>
        </a-col>
      </a-row>
      <div style="flex: 1;overflow: hidden;overflow-y: auto;">
        <a-row type="flex" :gutter="5" v-for="row in selectRows" style="padding:10px;border-bottom: 1px solid #eee;"
               :key="row.itemId" class="product"
        >
          <a-col>
            <a-popover placement="right">
              <template #content>
                <img :src="row.imgUrl"
                     style="width: 200px;height: 200px;"
                />
              </template>
              <img :src="row.imgUrl"
                   style="width: 42px;height: 42px;border-radius: 5px;"
              />
            </a-popover>
          </a-col>
          <a-col flex="1" class="two-line">
            {{ row.title }}
          </a-col>
          <a-col>
            <a-button size="small" danger type="link" @click="remove([row.itemId])">移除</a-button>
          </a-col>
        </a-row>
      </div>
    </div>
  </a-row>
  <a-divider style="margin-top: 10px;"/>
  <a-row type="flex">
    <a-col flex="1">
    </a-col>
    <a-col>
      <a-button type="primary" @click="()=>{
        if(selectRows.length===0){
          message.error('请选择宝贝');
          return;
        }
      emit('next',selectRows);
    }"
      >下一步
      </a-button>
    </a-col>
    <a-col flex="1">
    </a-col>
  </a-row>
</template>

<style lang="less" scoped>

.product {
  .title {
    // 一行超出隐藏
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .hover-show {
    display: none;
  }

  &:hover {
    .hover-show {
      display: block;
    }
  }
}

.top {
  background: rgb(249, 249, 249);
  padding: 10px;
  border-radius: 7px;
  color: #444;
}

.two-line {
  // 文字超出两行省略号
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 42px;
}
</style>
